package com.syni.mdd.sjb.community.base.controller.protect;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.syni.mdd.sjb.common.component.mybatis.community.entity.SjbQywxAdmin;
import com.syni.mdd.sjb.common.component.mybatis.community.entity.SjbQywxAdminRoleRelation;
import com.syni.mdd.sjb.common.component.mybatis.community.entity.SjbQywxCompany;
import com.syni.mdd.sjb.common.component.utils.common.utils.RestTemplateUtils;
import com.syni.mdd.sjb.common.component.utils.common.utils.ResultMapHelper;
import com.syni.mdd.sjb.community.base.auth.JwtTokenUtils;
import com.syni.mdd.sjb.community.base.config.QywxProperties;
import com.syni.mdd.sjb.community.base.config.QywxThirdApiProperties;
import com.syni.mdd.sjb.community.base.constants.Constants;
import com.syni.mdd.sjb.community.base.entity.bo.LoginInfoBo;
import com.syni.mdd.sjb.community.base.service.CommonUtilsServce;
import com.syni.mdd.sjb.community.base.service.SjbQywxAdminRoleRelationService;
import com.syni.mdd.sjb.community.base.service.SjbQywxAdminService;
import com.syni.mdd.sjb.community.base.service.SjbQywxCompanyService;
import com.syni.mdd.sjb.community.base.utils.OAUtils;
import com.syni.mdd.sjb.community.base.utils.QxwxThirdApiUtils;
import lombok.extern.log4j.Log4j2;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/login")
@Log4j2
public class LoginController {

    @Autowired
    CommonUtilsServce commonUtilsServce;

    @Autowired
    QxwxThirdApiUtils qxwxThirdApiUtils;

    @Autowired
    SjbQywxCompanyService sjbQywxCompanyService;

    @Autowired
    SjbQywxAdminService sjbQxwxAdminService;

    @Autowired
    SjbQywxAdminRoleRelationService sjbQywxAdminRoleRelationService;

    @Autowired
    QywxThirdApiProperties qywxThirdApiProperties;

    @Autowired
    QywxProperties qywxProperties;

    @Autowired
    JwtTokenUtils jwtTokenUtils;

    @Autowired
    SjbQywxAdminService sjbQywxAdminService;

    /**
     * 获取访问用户userid
     *
     * 请求地址：https://qyapi.weixin.qq.com/cgi-bin/service/getuserinfo3rd?suite_access_token=SUITE_ACCESS_TOKEN&code=CODE
     * 请求方式： GET
     * @parm1 SUITE_ACCESS_TOKEN
     * @parm2 oauth2授权成功返回的code
     */
    @PostMapping("/getUserinfo3rd")
    @ResponseBody
    public Map<String,Object> getUserInfo3rd(HttpServletRequest request, HttpServletResponse response,String code) throws IOException, WxErrorException {



        String suite_access_token = OAUtils.getSuiteAccessToken();

        String url = "https://qyapi.weixin.qq.com/cgi-bin/service/getuserinfo3rd?suite_access_token=" + suite_access_token + "&code=" + code;


        JSONObject jsonObj = JSON.parseObject(RestTemplateUtils.getForEntity(url,new HashMap<>()));

        String userTicket = jsonObj.getString("user_ticket");
        JSONObject result = getUserDetail3rd(userTicket);

        //final WxCpService wxCpService = WxCpConfiguration.getCpService(wxCpProperties.getAppConfigs().get(0).getAgentId());
        //WxCpProviderToken wxCpProviderToken = wxCpService.getOauth2Service().getUserInfo();


        return ResultMapHelper.success(result);
    }



    /**
     * 获取访问用户敏感信息
     *
     * 请求地址：https://qyapi.weixin.qq.com/cgi-bin/service/getuserdetail3rd?suite_access_token=SUITE_ACCESS_TOKEN
     * 请求方式： POST
     * @parm1 SUITE_ACCESS_TOKEN
     * @parm2 getUserInfo3rd获得的user_ticket
     */
    public static JSONObject getUserDetail3rd(String user_ticket) throws IOException {
        String suite_access_token = OAUtils.getSuiteAccessToken();
        String url = "https://qyapi.weixin.qq.com/cgi-bin/service/getuserdetail3rd?suite_access_token="+suite_access_token;

        Map<String,Object> jsonParms = new HashMap<String,Object>();
        jsonParms.put("user_ticket", user_ticket);
        JSONObject jsonObj = JSON.parseObject(RestTemplateUtils.postForEntityForJson(url,jsonParms));

        return jsonObj;
    }

    @GetMapping("/registerQywx")
    public void registerQywx(HttpServletResponse resp) throws IOException {
        String registerUrl = String.format("%s?register_code=%s",
                "https://open.work.weixin.qq.com/3rdservice/wework/register",qxwxThirdApiUtils.getRegisterCode(OAUtils.getProviderToken(),qywxProperties.getTemplateId()).getRegister_code());
        resp.sendRedirect(registerUrl);
    }


    @GetMapping("/noPlatformAdmin")
    public String noPm() {
        return "view/nopm";
    }


    @GetMapping("/loginFail")
    public String loginFail() {
        return "view/loginFail";
    }


    @GetMapping("/noAnZhuang")
    public String noAnZhuang() {
        return "view/noanzhuang";
    }

    @GetMapping("/home")
    public String home() {
        return "view/home";
    }

    @GetMapping("/getTestToken")
    @ResponseBody
    public String getTestToken(@RequestParam("adminId") Integer adminId) {
        SjbQywxAdmin sjbQywxAdmin = sjbQxwxAdminService.getById(adminId);
        return jwtTokenUtils.getToken(sjbQywxAdmin);
    }

    @GetMapping("/appInstall")
    public void applicationInstall(@RequestParam("auth_code") String authCode,HttpServletResponse resp) throws IOException {
        SjbQywxCompany sjbQywxCompany = sjbQywxCompanyService.addAuthCode(authCode);
        if(sjbQywxCompany == null){
            //安装页面
            resp.sendRedirect(commonUtilsServce.getInstallUrl());
        }
        SjbQywxAdmin sjbQywxAdmin = sjbQxwxAdminService.getBySuperAdminByCorpId(sjbQywxCompany.getCorpId());
        if (sjbQywxAdmin != null) {
            String token = jwtTokenUtils.getToken(sjbQywxAdmin);
            //首页页面
            resp.sendRedirect(String.format("%s?qwtoken=%s",qywxProperties.getCallbackDomain() + qywxProperties.getHomePage(),token));
        }
    }

    /**
     * 扫码登录回调
     *
     * 请求地址：https://qyapi.weixin.qq.com/cgi-bin/service/getuserdetail3rd?suite_access_token=SUITE_ACCESS_TOKEN
     * 请求方式： POST
     * @parm1 SUITE_ACCESS_TOKEN
     * @parm2 getUserInfo3rd获得的user_ticket
     */
    @GetMapping("/scanCodeLogin")
    public void scanCodeLogin(@RequestParam("auth_code") String authCode,HttpServletResponse resp) throws IOException {
        log.info("authCode:{}",authCode);
        //利用临时授权码获取用户信息
        LoginInfoBo loginInfoBo = qxwxThirdApiUtils.getLoginInfo(OAUtils.getProviderToken(),authCode);
        if(loginInfoBo.getErrcode() != null && !loginInfoBo.getErrcode().equals("0")){
            //定位到某个页面
            return;
        }
        String corpId = loginInfoBo.getCorp_info().getCorpid();
        String userid = loginInfoBo.getUser_info().getUserid();
        if(!loginInfoBo.getUsertype().equals(LoginInfoBo.USER_TYPE_1)){
            //判断是否是平台超管
            SjbQywxAdmin sjbQywxAdmin = sjbQxwxAdminService.getBySuperAdminByCorpId(corpId);
            if(sjbQywxAdmin != null && sjbQywxAdmin.getUserid().equals(userid)){
                //平台超管
            }else {
                //判断是否是平台管理员
                sjbQywxAdmin = sjbQxwxAdminService.getByCorpIdAndUserId(corpId,userid);
                if(sjbQywxAdmin == null) {
                    //不是平台管理员
                    resp.sendRedirect(qywxProperties.getCallbackDomain() + qywxProperties.getNoPlatformAdmin());
                    return ;
                }
                SjbQywxAdminRoleRelation sjbQywxAdminRoleRelation = sjbQywxAdminRoleRelationService.getQywxAdminId(sjbQywxAdmin.getId());
                if(sjbQywxAdminRoleRelation == null){
                    resp.sendRedirect(qywxProperties.getCallbackDomain() + qywxProperties.getNoPlatformAdmin());
                    return ;
                }
                if(!sjbQywxAdminRoleRelation.getRoleId().equals(Constants.QYWX_ADMIN_ROLE_PM)){
                    resp.sendRedirect(qywxProperties.getCallbackDomain() + qywxProperties.getNoPlatformAdmin());
                    return ;
                }
            }
            //判断是否安装
            SjbQywxCompany sjbQywxCompany = sjbQywxCompanyService.getByCompanyId(loginInfoBo.getCorp_info().getCorpid());
            if(sjbQywxCompany == null){
                //没安装
                resp.sendRedirect(commonUtilsServce.getInstallUrl());
                return;
            }
            String token = jwtTokenUtils.getToken(sjbQywxAdmin);
            //首页页面
            resp.sendRedirect(String.format("%s?qwtoken=%s",qywxProperties.getCallbackDomain() + qywxProperties.getHomePage(),token));
            return;
        }
        //判断当前企业是否进行安装应用
        SjbQywxCompany sjbQywxCompany = sjbQywxCompanyService.getByCompanyId(loginInfoBo.getCorp_info().getCorpid());
        if(sjbQywxCompany == null){
            //安装页面
            resp.sendRedirect(commonUtilsServce.getInstallUrl());
            return;
        }
        //保存至超级管理员
        SjbQywxAdmin sjbQywxAdmin = sjbQxwxAdminService.getByCorpIdAndUserId(corpId,userid);
        if(sjbQywxAdmin == null){
            resp.sendRedirect(qywxProperties.getCallbackDomain() + qywxProperties.getLoginFail());
            return;
        }
        String token = jwtTokenUtils.getToken(sjbQywxAdmin);
        //首页页面
        resp.sendRedirect(String.format("%s?qwtoken=%s",qywxProperties.getCallbackDomain() + qywxProperties.getHomePage(),token));
    }

    @GetMapping("/installMddSjbApp")
    public void installMddSjbApp(HttpServletResponse resp) throws IOException{
        resp.sendRedirect(commonUtilsServce.getInstallUrl());
    }

    @GetMapping("/toLogin")
    public void toLogin(HttpServletResponse resp) throws IOException{
        resp.sendRedirect(commonUtilsServce.getLoginUrl());
    }

    @GetMapping("/toQywxLogin")
    public String toQywxLogin(Model modelAndView){
        modelAndView.addAttribute("installMddSjbApp",commonUtilsServce.getInstallUrl());
        modelAndView.addAttribute("registerQywx",commonUtilsServce.getRegisterUrl());
        modelAndView.addAttribute("toLogin",commonUtilsServce.getLoginUrl());
        return "view/index";
    }
}
